package dao;

import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public abstract class BaseDao <T> {
	private Class<T> entityClass;
	
	public static EntityManager em;
	static {
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("EnrollmentManagement-PU");
		em = emf.createEntityManager();
	}
	
	@SuppressWarnings("unchecked")
	public BaseDao() {
		ParameterizedType supperClass = (ParameterizedType) getClass().getGenericSuperclass();
		this.entityClass = (Class<T>) supperClass.getActualTypeArguments()[0];
	}
	
	public void save(T entity) {
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		em.persist(entity);
		tx.commit();
	}
	
	public T findById(Long id) {
		return em.find(entityClass, id);
	}
	
	public void delete(T entity) {
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		em.remove(entity);
		tx.commit();
	}

	public void merge(T entity) {
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		em.merge(entity);
		tx.commit();
	}
}
